package com.learn.core.controller.learn;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.BeanProperty;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.domain.view.CourseEnroll;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.dto.LCourseDTO;
import com.learn.core.dto.LTeacherDTO;
import com.learn.core.service.*;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @auther CodeGenerator
 * @create 2021-03-08 22:50:00
 * @describe 我的学习
 */
@Api("我的学习")
@RestController
@RequestMapping("/learn/myLearn")
public class MyLearnController extends WebController<LCourse> {

    @Autowired
    private ILCourseService iLCourseService;
    @Autowired
    private ILTeacherService iLTeacherService;
    @Autowired
    private ILCourseSortService ilCourseSortService;
    @Autowired
    private ILChapterService ilChapterService;
    @Autowired
    private ILCoursewareService ilCoursewareService;
    @Autowired
    private ICourseEnrollService iCourseEnrollService;
    @Autowired
    private ILEnrollService ilEnrollService;
    @Autowired
    private ILLearnService ilLearnService;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //列表
    @ApiOperation(value = "获取列表--有效课程")
    @UserLoginToken
    @PostMapping("/courseList")
    public PageResult<CourseEnroll> list(@RequestBody LCourseDTO lCourseDTO, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lCourseDTO==null||lCourseDTO.getPage()==null||lCourseDTO.getRows()==null){
                return new PageResult<CourseEnroll>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCourseDTO.getPage(),lCourseDTO.getRows());
            QueryWrapper<CourseEnroll> queryWrapper = new QueryWrapper<CourseEnroll>();
            if(StringUtils.isNotEmpty(lCourseDTO.getLikeParameter()))
                queryWrapper.like("course_name",lCourseDTO.getLikeParameter());
            if(StringUtils.isNotEmpty(lCourseDTO.getCourseSortId()))
                queryWrapper.eq("course_sort_id",lCourseDTO.getCourseSortId());
            if(StringUtils.isNotEmpty(lCourseDTO.getTeacher()))
                queryWrapper.eq("teacher",lCourseDTO.getTeacher());
            if(StringUtils.isNotEmpty(lCourseDTO.getCourseType()))
                queryWrapper.eq("course_type",lCourseDTO.getCourseType());
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("release_stutes","1");
            queryWrapper.ge("course_fail_time",formatter.format(new Date()));
            if(lCourseDTO.getSortType()!=null&&lCourseDTO.getSortBy()!=null)
                queryWrapper.orderBy(true,lCourseDTO.getSortType(),lCourseDTO.getSortBy());
            Page<CourseEnroll> courseEnrolls = (Page<CourseEnroll>) iCourseEnrollService.list(queryWrapper);
            if (CollectionUtils.isEmpty(courseEnrolls)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (CourseEnroll courseEnroll : courseEnrolls) {
                LTeacher lTeacher = iLTeacherService.getById(courseEnroll.getTeacher());
                if(null != lTeacher){
                    courseEnroll.setTeacherName(lTeacher.getTeacherName());
                }
                LCourseSort lCourseSort = ilCourseSortService.getById(courseEnroll.getCourseSortId());
                if(null != lCourseSort){
                    courseEnroll.setCourseSortName(lCourseSort.getCourseSortName());
                }
            }
            // 返回
            return new PageResult(courseEnrolls.getTotal(), courseEnrolls, ResultEnum.SUCCESS);
        }catch (Exception e){
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //课程分类列表
    @ApiOperation(value = "课程分类列表")
    @UserLoginToken
    @GetMapping("/courseSortList")
    public CommonResult<Object> courseSortList(@RequestParam("id")String parentNode){
        try {
            QueryWrapper<LCourseSort> queryWrapper = new QueryWrapper<LCourseSort>();
            queryWrapper.eq("parent_node",parentNode);
            List<LCourseSort> lCourseSorts = ilCourseSortService.list(queryWrapper);
            if(lCourseSorts.size()>0)
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lCourseSorts);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //主讲人列表
    @ApiOperation(value = "主讲人列表")
    @UserLoginToken
    @PostMapping("/teacherList")
    public CommonResult<Object> teacherList(){
        try {
            QueryWrapper<LTeacher> queryWrapper = new QueryWrapper<LTeacher>();
            queryWrapper.eq("stutes","1");
            List<LTeacher> lTeachers = iLTeacherService.list(queryWrapper);
            if(lTeachers.size()>0)
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lTeachers);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }


    //课程详情
    @ApiOperation(value = "课程详情")
    @UserLoginToken
    @GetMapping("/courseInfo")
    public CommonResult<Object> info( @RequestParam("id")String courseId, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (courseId==null){
                return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
            }
            QueryWrapper<LCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("course_id",courseId);
            LCourse lCourse = iLCourseService.getOne(queryWrapper);
            if(null != lCourse){
                QueryWrapper<LChapter> lChapterQueryWrapper = new QueryWrapper<>();
                lChapterQueryWrapper.eq("course_id",lCourse.getCourseId());
                List<LChapter> lChapterList = ilChapterService.list(lChapterQueryWrapper);
                for (LChapter lChapter : lChapterList) {
                    LCourseware lCourseware = ilCoursewareService.getById(lChapter.getCoursewareId());
                    lChapter.setlCourseware(lCourseware);
                    QueryWrapper<LLearn> learnQueryWrapper = new QueryWrapper<>();
                    learnQueryWrapper.eq("user_id",userId);
                    learnQueryWrapper.eq("chapter_id",lChapter.getChapterId());
                    learnQueryWrapper.eq("courseware_id",lChapter.getCoursewareId());
                    LLearn learn = ilLearnService.getOne(learnQueryWrapper);
                    lChapter.setlLearn(learn);
                }
                lCourse.setlChapters(lChapterList);
            }
            // 返回
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,lCourse);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //课程学习情况
    @ApiOperation(value = "课程学习情况")
    @UserLoginToken
    @GetMapping("/learningStatus")
    public CommonResult<Object> learningStatus( @RequestParam("courseId")String courseId,
                                                @RequestParam("chapterId")String chapterId, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (courseId==null){
                return (CommonResult) ResultUtil.error(ResultEnum.LOAD_ERROR);
            }
            QueryWrapper<LCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("course_id",courseId);
            LCourse lCourse = iLCourseService.getOne(queryWrapper);
            Map<String,Object> map = new HashMap<>();
            map.put("id",lCourse.getCourseId());
            map.put("classHours",lCourse.getClassHours());
            // 未学习人数
            QueryWrapper<LEnroll> enrollQueryWrapper = new QueryWrapper<>();
            enrollQueryWrapper.eq("course_id",courseId);
            enrollQueryWrapper.eq("user_id",userId);
            enrollQueryWrapper.eq("stutes","0");
            int notCount = ilEnrollService.count(enrollQueryWrapper);
            map.put("notCount",notCount);
            enrollQueryWrapper = new QueryWrapper<>();
            enrollQueryWrapper.eq("course_id",courseId);
            enrollQueryWrapper.eq("user_id",userId);
            enrollQueryWrapper.eq("stutes","1");
            int ingCount = ilEnrollService.count(enrollQueryWrapper);
            map.put("ingCount",ingCount);
            enrollQueryWrapper = new QueryWrapper<>();
            enrollQueryWrapper.eq("course_id",courseId);
            enrollQueryWrapper.eq("user_id",userId);
            List inlist = new ArrayList();
            inlist.add(2);inlist.add(3);inlist.add(4);
            enrollQueryWrapper.in("stutes",inlist);
            int alreadyCount = ilEnrollService.count(enrollQueryWrapper);
            map.put("alreadyCount",alreadyCount);

            enrollQueryWrapper = new QueryWrapper<>();
            enrollQueryWrapper.eq("course_id",courseId);
            enrollQueryWrapper.eq("user_id",userId);
            inlist = new ArrayList();
            inlist.add(3);inlist.add(4);
            enrollQueryWrapper.in("stutes",inlist);
            int graduation = ilEnrollService.count(enrollQueryWrapper);
            if(graduation >0)
                map.put("graduation","1");
            else
                map.put("graduation","0");
            // 课程进度
            QueryWrapper<LEnroll> lEnrollQueryWrapper = new QueryWrapper<>();
            lEnrollQueryWrapper.eq("course_id",courseId);
            lEnrollQueryWrapper.eq("user_id",userId);
            LEnroll lEnroll = ilEnrollService.getOne(lEnrollQueryWrapper);
            map.put("courseSpeed",lEnroll.getSpeed());
            // 课件进度
            QueryWrapper<LLearn> learnQueryWrapper = new QueryWrapper<>();
            learnQueryWrapper.eq("enroll_id",lEnroll.getEnrollId());
            learnQueryWrapper.eq("chapter_id",chapterId);
            LLearn learn = ilLearnService.getOne(learnQueryWrapper);
            if(null != learn){
                map.put("chapterSpeed",learn.getSpeed());
            }else{
                map.put("chapterSpeed","0");
            }

            // 返回
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //记录学习
    @ApiOperation(value = "记录学习")
    @PostMapping("/recordLearning")
    @UserLoginToken
    @Log(title = "记录学习", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> register(@RequestBody LLearn lLearn, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lLearn==null){
                return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
            }
            if(StringUtils.isEmpty(lLearn.getEnrollId()))
                return (CommonResult) ResultUtil.error(ResultEnum.NOT_ENROLL_ID);
            if(StringUtils.isEmpty(lLearn.getChapterId()))
                return (CommonResult) ResultUtil.error(ResultEnum.NOT_CHAPTER_ID);
            if(StringUtils.isEmpty(lLearn.getCoursewareId()))
                return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSEWARE_ID);
            if(StringUtils.isEmpty(lLearn.getLearnTime()))
                return (CommonResult) ResultUtil.error(ResultEnum.NOT_LEARN_TIME);

            LCourseware lCourseware = ilCoursewareService.getById(lLearn.getCoursewareId());
            if(null != lCourseware){
                String coursehours = lCourseware.getCoursewareHours();
                Double hours = Double.valueOf(coursehours) * 60 * 60;
                Double speed = Double.valueOf(Math.round(lLearn.getLearnTime()/hours*100));
                if(speed >= 100)
                    lLearn.setSpeed("100");
                else
                    lLearn.setSpeed(speed.toString());
            }

            if(null != lLearn.getLearnId()){
                LLearn learn = ilLearnService.getById(lLearn.getLearnId());
                BigDecimal big = new BigDecimal(learn.getSpeed());
                if(learn.getLearnTime() < lLearn.getLearnTime() && big.compareTo(new BigDecimal(100)) < 0){
                    lLearn.setUpdateUser(userId);
                    lLearn.setUpdateTime(new Date());
                    ilLearnService.updateById(lLearn);
                }
            }else{
                lLearn.setUserId(Integer.parseInt(userId));
                lLearn.setCreateUser(userId);
                lLearn.setCreateTime(new Date());
                lLearn.setStutes("1");
                ilLearnService.save(lLearn);
            }

            LEnroll lEnroll = ilEnrollService.getById(lLearn.getEnrollId());
            if(null != lEnroll){
                LCourse lCourse = iLCourseService.getById(lEnroll.getCourseId());
                String coursehours = lCourse.getClassHours();
                Double hours = Double.valueOf(coursehours) * 60 * 60;
                Double learn =lLearn.getLearnTime()/hours*100;
                BigDecimal bigDecimal = new BigDecimal(lEnroll.getSpeed());
                BigDecimal big = bigDecimal.add(new BigDecimal(learn));
                big = big.setScale(2, RoundingMode.HALF_UP);
                Double finish = Double.valueOf(lLearn.getLearnTime())/60/60;
                BigDecimal fbig = new BigDecimal(finish);
                fbig = fbig.setScale(2, RoundingMode.HALF_UP);
                lEnroll.setFinishHours(fbig.doubleValue());
                // 判断是否学习完成
                if(big.compareTo(new BigDecimal(100)) > 0) {
                    lEnroll.setStutes("2");
                    lEnroll.setSpeed("100");
                }else {
                    lEnroll.setStutes("1");
                    lEnroll.setSpeed(big.toString());
                }
                ilEnrollService.updateById(lEnroll);
            }
            return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //申请结业
    @ApiOperation(value = "申请结业")
    @GetMapping("/graduation")
    @UserLoginToken
    @Log(title = "申请结业", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object>graduation(@RequestParam("courseId")Integer courseId, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            QueryWrapper<CourseEnroll> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("course_id",courseId);
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("release_stutes","1");
            CourseEnroll courseEnroll = iCourseEnrollService.getOne(queryWrapper);
            if(null != courseEnroll){
                if(!"2".equals(courseEnroll.getStutes()))
                    return (CommonResult)ResultUtil.error(ResultEnum.NOT_COURSE_STATE);
                LEnroll lEnroll = new LEnroll();
                lEnroll.setEnrollId(courseEnroll.getEnrollId());
                lEnroll.setStutes("3");
                if(ilEnrollService.updateById(lEnroll))
                    return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        } catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}
